package org.icress.fusion.shiro

import org.apache.shiro.crypto.hash.Sha512Hash

class UserService {

    static transactional = true 

    def save(User userInstance) {
        //get user
        return userInstance.validate() && userInstance.save(flush: true)
    }
    
    def update(User userInstance) {
        //get user
        def success = false
        User.withTransaction{ status ->
            //def currentUser = User.findByUsername( SecurityUtils.getSubject().getPrincipal() )
            success = userInstance.validate() && userInstance.save(flush: true)
            if(!success){
                status.setRollbackOnly()
            }
        }
        return success
    }
    
    def resetPassword(User userInstance, String password, String passwordConfirm){
        def result = false

        User.withTransaction{ status ->
            if(password != null && !password.trim().equals('') && password.size() >= 8 && password.equals(passwordConfirm)){
                userInstance.passwordHash = new Sha512Hash(password).toHex()
                result = userInstance.validate() && userInstance.save(flush: true)
                if(result != true){
                    status.setRollbackOnly()
                }
            }else{
                userInstance.errors.reject(
                    'user.passwordHash.doesnotmatch',                                    // Error code within the grails-app/i18n/message.properties
                    ['password', 'class User'] as Object[],                          // Groovy list cast to Object[]
                    '[Property [{0}] of class [{1}] does not match confirmation]')   // Default mapping string

                // The following helps with field highlighting in your view
                userInstance.errors.rejectValue(
                    'passwordHash',                                                 // Field in view to highlight using <g:hasErrors> tag
                    'user.password.doesnotmatch')                               // i18n error code
                
            }
        }
        log.info("${result}=${userInstance}")
        return result
    }
}
